//
//  LXLoginViewController.m
//  cat
//
//  Created by imera on 16/3/9.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "LXLoginViewController.h"
#import "LXLoginView.h"
#import "LXNavBarView.h"
#import "LXRegisterViewController.h"
#import "AFNetworking.h"
#import "MBProgressHUD+MJ.h"

@interface LXLoginViewController () <LXNavBarViewDelegate,LXLoginViewDelegate>

@end

@implementation LXLoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self initNavBar];
    
    [self addLoginView];
}

#pragma mark 自定义导航条
- (void)initNavBar
{
    LXNavBarView *navBarView = [[LXNavBarView alloc]init];
    navBarView.frame = CGRectMake(0, 20, self.view.frame.size.width, 40);
    navBarView.myDelegate = self;
    navBarView.leftTitle = @"登录";
    [self.view addSubview:navBarView];
}

#pragma mark - LXNavBarView代理方法
- (void)popCurrentViewController:(LXNavBarView *)navBarView
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - 添加登录界面
- (void)addLoginView
{
    LXLoginView *loginView = [[LXLoginView alloc]init];
    loginView.myDelegate = self;
    CGFloat loginViewW = self.view.frame.size.width;
    CGFloat loginViewH = self.view.frame.size.height - 60;
    CGFloat loginViewX = 0;
    CGFloat loginViewY = self.view.frame.size.height - loginViewH;
    loginView.frame = CGRectMake(loginViewX, loginViewY, loginViewW, loginViewH);
    [self.view addSubview:loginView];
}

#pragma mark - 登录视图代理
- (void)loginView:(LXLoginView *)loginView userName:(NSString *)userName password:(NSString *)password
{
    //登录
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSString *url = @"http://cat666.com/cat666-interface/index.php/index/check";
    [mgr POST:url parameters:@{@"user":userName,@"password":password} success:^(AFHTTPRequestOperation *operation, id response) {
        NSDictionary *dict = response;
        if (dict.allKeys.count == 1) {
            [MBProgressHUD showError:@"用户名或密码错误"];
        }else{
            [MBProgressHUD showSuccess:@"登录成功"];
            [[NSUserDefaults standardUserDefaults]setObject:userName forKey:@"userName"];
            [[NSUserDefaults standardUserDefaults]setObject:dict[@"id"] forKey:@"userId"];
            [[NSUserDefaults standardUserDefaults]setObject:password forKey:@"password"];
        
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        [MBProgressHUD showError:@"您的网络开小差了..."];
    }];
}

- (void)userRegister:(LXLoginView *)loginView
{
    LXRegisterViewController *registerVc = [[LXRegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVc animated:YES];
}
@end
